package com.dinzeer.slashblade_useful_addon.events;

import com.dinzeer.legendreliclib.lib.compat.slashblade.SlashEffect;
import com.dinzeer.slashblade_useful_addon.*;

import com.dinzeer.slashblade_useful_addon.config.Config;
import mods.flammpfeil.slashblade.capability.concentrationrank.CapabilityConcentrationRank;
import mods.flammpfeil.slashblade.capability.slashblade.ISlashBladeState;
import mods.flammpfeil.slashblade.event.SlashBladeEvent;
import mods.flammpfeil.slashblade.init.SBItems;
import mods.flammpfeil.slashblade.item.ItemSlashBlade;
import mods.flammpfeil.slashblade.slasharts.Drive;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.List;
import java.util.stream.Collectors;

@Mod.EventBusSubscriber
public class SUAevents {


    // 常量提取
    private static final int MIN_SOUL_COUNT = 1000;
    private static final double SLASH_CHANCE = 0.5;

    // 共享逻辑提取
    static int getPlayerRank(LivingEntity player) {
        return player.getCapability(CapabilityConcentrationRank.RANK_POINT)
                .map(r -> r.getRank(player.level().getGameTime()).level)
                .orElse(0);
    }

    private static void handleSlashLogic(Player player, SlashBladeEvent.DoSlashEvent event, ISlashBladeState state) {
        if (Math.random() <= SLASH_CHANCE) {
            executeSlashAttack(player, event, 20, 0.2f);
        }

        if (player.hasEffect(MobEffects.DAMAGE_BOOST)) {
            executeSlashAttack(player, event, 22, 0.1f);
        }
    }

    private static void executeSlashAttack(Player player, SlashBladeEvent.DoSlashEvent event,
                                           int charge, float speed) {
        Drive.doSlash(player, event.getRoll(), charge, Vec3.ZERO,
                event.isCritical(), event.getDamage(), speed);
    }



    @SubscribeEvent
    public static void onFurnaceFuel(FurnaceFuelBurnTimeEvent event) {
        ItemStack fuel = event.getItemStack();

        if (fuel.getItem() == SBItems.proudsoul_tiny) {
            event.setBurnTime(1200); // 6个物品 × 200刻/个
        }
        else if (fuel.getItem() == SBItems.proudsoul) {
            event.setBurnTime(8000); // 40个物品 × 200刻/个
        }
    }



    private static void handleSoulTrapezoid(Player player, ISlashBladeState state, SlashBladeEvent.BladeStandAttackEvent event) {



        CompoundTag nbt = player.getMainHandItem().getOrCreateTag();


        if (!player.isShiftKeyDown()
                && state.getKillCount() >= 1000
                &&!nbt.contains("killcount")) {
            int count=state.getKillCount() / 100;
            for(int i = 0; i < count; i++) {
                ItemStack kill = SBItems.proudsoul_trapezohedron.getDefaultInstance();

                // 添加NBT数据
                CompoundTag tag = kill.getOrCreateTag();
                tag.putInt("killcount", 100);

                if (!player.level().isClientSide) {
                    player.spawnAtLocation(kill);
                }
            }
            state.setKillCount(0);
            player.getMainHandItem().shrink(1);
            event.setCanceled(true);
        }else if (!player.isShiftKeyDown()
                &&nbt.contains("killcount")
        ){
            state.setKillCount(state.getKillCount()+nbt.getInt("killcount"));
            player.getMainHandItem().shrink(1);
            event.setCanceled(true);
        }


        if (player.isShiftKeyDown() && state.getProudSoulCount() >= Config.soulCost) {
            int count = state.getProudSoulCount() / Config.soulCost;

            for(int i = 0; i < count; i++) {
                ItemStack soul = createEnchantedSoul(player);
                if (!player.level().isClientSide) {
                    player.spawnAtLocation(soul);
                }
            }

            state.setProudSoulCount(state.getProudSoulCount() % Config.soulCost);
            player.getMainHandItem().shrink(1);
            event.setCanceled(true);
        }
    }

    private static ItemStack createEnchantedSoul(Player player) {
        ItemStack soul = SBItems.proudsoul_tiny.getDefaultInstance();
        List<Enchantment> validEnchants = BuiltInRegistries.ENCHANTMENT.stream()
                .filter(e -> e.category == EnchantmentCategory.WEAPON || e.category == EnchantmentCategory.BOW)
                .collect(Collectors.toList());

        if (!validEnchants.isEmpty()) {
            Enchantment selected = validEnchants.get(player.getRandom().nextInt(validEnchants.size()));
            soul.enchant(selected, 1);
        }
        return soul;
    }

    private static void handleNetherStarUpgrade(Player player, ISlashBladeState state, SlashBladeEvent.BladeStandAttackEvent event) {
        if (state.getBaseAttackModifier() < Config.maxAttackModifier) {
            state.setBaseAttackModifier(state.getBaseAttackModifier() + 1);
            player.getMainHandItem().shrink(1);
            event.setCanceled(true);
        }
    }







    @SubscribeEvent
    public static void dohurt(LivingHurtEvent event){
        if (event.getEntity() == null || event.getSource().getEntity() == null) {
            return; // 提前终止无效事件
        }
        if (!Config.xpadd){return;}

         if (event.getSource().getEntity() instanceof Player player){


             if (player.getMainHandItem().getItem() instanceof ItemSlashBlade a){
                 int xplevel=player.experienceLevel;
                 Float extra=(xplevel/10)*0.01F;


                 System.out.println(extra);
                 System.out.println(event.getAmount());
                 event.setAmount(event.getAmount()*(1+extra));
                 System.out.println(event.getAmount());
             }



         }

    }

    public static int intvoid(float v){
       int a= (int) Math.ceil(v/50);
        return a;
    }




    @SubscribeEvent
    public static void doslash(SlashBladeEvent.DoSlashEvent event) {
        if (!Config.enableDoSlash) return;

        if (!(event.getUser() instanceof Player player)) return;

        ISlashBladeState state = event.getSlashBladeState();
        int rank = getPlayerRank(player);
        if (rank >= 4 && state.getProudSoulCount() >= MIN_SOUL_COUNT) {
            handleSlashLogic(player, event, state);
        }
        if (rank >= 6 && state.getProudSoulCount() >= MIN_SOUL_COUNT){

            if (Config.enabless){
                SlashEffect.SakuraEnd.doSlash(player
                            ,event.getRoll(),
                    Vec3.ZERO,
                    event.isCritical()
                    ,event.isCritical()
                    ,event.getDamage()
                    );
                SlashEffect.SakuraEnd.doSlash(player
                    ,event.getRoll(),
                    Vec3.ZERO,
                    event.isCritical()
                    ,event.isCritical()
                    ,event.getDamage()
            );
        }
        }
    }
    @SubscribeEvent
    public static void BladeStandAttack(SlashBladeEvent.BladeStandAttackEvent event) {
        if (!(event.getDamageSource().getEntity() instanceof Player player)) return;

        ISlashBladeState state = event.getSlashBladeState();
        ItemStack mainHand = player.getMainHandItem();

        // 灵魂结晶功能
        if (Config.enableSoulTrapezoid && mainHand.is(SBItems.proudsoul_trapezohedron)) {
            handleSoulTrapezoid(player, state, event);
        }

        // 下界之星功能
        if (Config.enableNetherStarUpgrade && mainHand.is(Items.NETHER_STAR)) {
            handleNetherStarUpgrade(player, state, event);
        }
    }







}
